package com.myworld.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;  //可解决压缩文件乱码问题
/**
 * restful风格 文件下载接口
 * @author 倔小犟
 */
@Controller
public class RestFileController {
	private static final Logger log = LoggerFactory.getLogger(RestFileController.class);
	
	@Autowired
	private RestTemplate restTemplate;
	
	@PostMapping(value="/download",
			produces={MediaType.MULTIPART_FORM_DATA_VALUE	
	})
	public ResponseEntity<byte[]> download(@RequestBody String filePath){
		if(StringUtils.isNoneBlank(filePath)){
			try{
				String fileName=filePath.substring(filePath.lastIndexOf("/")+1,filePath.length());
				HttpHeaders headers=new HttpHeaders();				
				headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("UTF-8"),"ISO8859-1"));
				headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
				
				File templateFile=new File(filePath);			
				byte[] bytes=FileUtils.readFileToByteArray(templateFile);
				return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED);
			}catch(Exception e){
				e.printStackTrace();
				return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
			}
		}else{
			return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
		}
	}
	
	/**
	 * 模拟其他系统下载单个文件
	 */
	@RequestMapping(value = "/downloadFile", produces = {MediaType.MULTIPART_FORM_DATA_VALUE})
	public ResponseEntity<byte[]> downloadFile(HttpServletRequest request, HttpServletResponse response){		
		return restTemplate.postForEntity("http://127.0.0.1:9090/download", "E:/学习书籍/初识 Spring Security - v1.1.pdf", byte[].class);
	}
	
	/**
	 * 模拟：多个文件，通过压缩包形式下载
	 */
	@RequestMapping(value = "/downloadZipFile", produces = {MediaType.MULTIPART_FORM_DATA_VALUE})
	public void downloadZipFile(HttpServletRequest request, HttpServletResponse response){
		//测试用例
		List<String> filePathList = Arrays.asList("E:/学习书籍/初识 Spring Security - v1.1.pdf");

		String zipName = "测试中文.zip";
		ZipOutputStream zipOutputStream = null;
		try {
			//response.setContentType("application/octet-stream;charset=utf-8");
			response.setHeader("Content-Disposition","attachment; filename="+zipName);
			zipOutputStream = new ZipOutputStream(response.getOutputStream());
			zipOutputStream.setEncoding("GBK");
			
			// 设置下载文件类型
			response.setContentType("application/octet-stream;charset=ISO-8859-1");
			// 设置下载文件头
			String agent = request.getHeader("USER-AGENT");
			if (null != agent && -1 != agent.indexOf("MSIE") || null != agent && -1 != agent.indexOf("Trident")) {// ie
				zipName = java.net.URLEncoder.encode(zipName, "UTF8");
				response.setHeader("Content-Disposition", "filename=\"" + zipName + "\"");
			} else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等
				zipName = new String(zipName.getBytes("UTF-8"), "iso-8859-1");
				response.setHeader("Content-Disposition", "attachment; filename=\"" + zipName + "\"");
			}
			
			//遍历每个文件，并将文件添加到压缩包中
			for(String filePath : filePathList){
				String tmpFileName = filePath.substring(filePath.lastIndexOf("/")+1,filePath.length());
				//从RESTful接口获取文件字节
				ResponseEntity<byte[]> responseEntity = restTemplate.postForEntity("http://127.0.0.1:9090/download", filePath, byte[].class);
				
				if(responseEntity != null && responseEntity.getBody() != null){
					zipOutputStream.putNextEntry(new ZipEntry(tmpFileName));
					zipOutputStream.write(responseEntity.getBody());
					zipOutputStream.flush();
					zipOutputStream.closeEntry();
				}
			}
			response.flushBuffer();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(zipOutputStream != null){
					zipOutputStream.close();
				}
			} catch (IOException e) {
				//ignore
			}
		}
	}

}
